from base import *
from tag import Tag
from rootnode import RootNode
from django.utils.translation import ugettext as _

class Argument(RootNode):
    class Meta(Node.Meta):
        proxy = True

    answer_count = DenormalizedField("children", ~models.Q(state_string__contains="(deleted)"), node_type="answer")
    accepted_count = DenormalizedField("children", ~models.Q(state_string__contains="(deleted)"), node_type="answer", marked=True)
    favorite_count = DenormalizedField("actions", action_type="favorite", canceled=False)

    friendly_name = _("argument")

    def _other_headline(self):

        if self.nis.promoted:
            return _('[+] ') + self.title

        return self.title

    @property
    def accepted_answers(self):
        return self.answers.filter(~models.Q(state_string__contains="(deleted)"), marked=True)

    @models.permalink    
    def get_absolute_url(self):
        return ('argument', (), {'id': self.id, 'slug': django_urlquote(slugify(self.title))})
        
    def get_revision_url(self):
        return reverse('argument_revisions', args=[self.id])

    def get_related_arguments(self, count=10):
        cache_key = '%s.related_arguments:%d:%d' % (settings.APP_URL, count, self.id)
        related_list = cache.get(cache_key)

        if related_list is None:
            related_list = Argument.objects.filter_state(deleted=False,published=True).values('id').filter(tags__id__in=[t.id for t in self.tags.all()]
            ).exclude(id=self.id).annotate(frequency=models.Count('id')).order_by('-frequency')[:count]
            cache.set(cache_key, related_list, 60 * 60)

        return [Argument.objects.get(id=r['id']) for r in related_list]
    



class ArgumentSubscription(models.Model):
    user = models.ForeignKey(User)
    argument = models.ForeignKey(Node)
    auto_subscription = models.BooleanField(default=True)
    last_view = models.DateTimeField(default=datetime.datetime.now())

    class Meta:
        app_label = 'forum'


class ArgumentRevision(NodeRevision):
    class Meta:
        proxy = True
        
